<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">创建新角色</el-button>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="名称" width="180">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="nameZh" label="中文名称">
        <template slot-scope="scope">
          {{ scope.row.nameZh }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="order" label="顺序">
        <template slot-scope="scope">
          {{ scope.row.order }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--隐藏表单-->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">
      <el-form :model="role" label-width="90px" :rules="rules" label-position="left">
        <el-form-item label="名字" prop="name">
          <el-input v-model="role.name" placeholder="角色名称"/>
        </el-form-item>
        <el-form-item label="中文名称" prop="nameZh">
          <el-input v-model="role.nameZh" placeholder="中文名称"/>
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input v-model="role.order" type="number" placeholder="排序"/>
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="tree"
            :data="data"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkKeys"
            :expand-on-click-node="true"
            :check-on-click-node="true"
            :check-strictly="true"
          >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
        </span>
          </el-tree>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, addRole, deleteRole, modifyRole } from '@/api/role'
import { deepClone } from '@/utils'
import { addRolePermission, getPermission, getRolePermission } from '@/api/permission'

const defaultRole = {
  id: '',
  name: '',
  nameZh: '',
  order: '',
}

export default {
  name: 'RoleList',
  comments: {},
  created() {
    // Mock: get all routes and roles list from server
    this.getRoles()
    this.getPermissionTree()
  },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      data: {},
      defaultProps: {
        children: 'children',
        label: 'title',
      },
      checkKeys: [2, 3],
      permissionIds: [],
      rules: {
        name: [{ required: true, message: '非空' }],
        nameZh: [{ required: true, message: '非空' }],
        order: [{ required: true, message: '非空' }]
      }
    }
  },
  computed: {
  },
  methods: {
    async getRoles() {
      const res = await getRoles()
      this.rolesList = res.data.rows
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      this.dialogType = 'new'
      this.dialogVisible = true
      const empty = []
      this.$refs.tree.setCheckedKeys(empty, false)
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = deepClone(scope.row)
      getRolePermission(this.role.id).then((response) => {
        this.$refs.tree.setCheckedKeys(response.data, false)
      })
      // 根据角色获取权限
      this.$nextTick(() => {
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除这个角色吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteRole(row.id, 'FALSE')
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      const checkedKeys = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      console.log(checkedKeys)
      if (isEdit) {
        await modifyRole(this.role.id, this.role)
        await addRolePermission(this.role.id, checkedKeys)
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].id === this.role.id) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        await addRole(this.role).then((response)=>{
          addRolePermission(response.data, checkedKeys)
        })
      }
      await this.getRoles()
      // const { id, name, nameZh, order } = this.role
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功",
        type: 'success'
      })
    },
    async getPermissionTree() {
      getPermission().then((response) => {
        this.data = response.data.children;
      });
    },
  }
}
</script>

<style scoped>

</style>
